var appPath = getAppPath();
var uploader = null;
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var validFile = false;

$(function(){
	initJspGrid();
	
	// 初始化 视频播放 点击红叉  停止播放
	$('#playVideoDlg').window({
	       onBeforeClose:function(){ 
	    	   var myVideo = document.getElementsByTagName('video')[0];
	    	   myVideo.pause(); // 暂停视频 播放
	       }
	});
	$('#playMediaDlg').window({
		onBeforeClose:function(){ 
			var audio = document.getElementById('audio'); 
			audio.pause();// 这个就是暂停 // 暂停音频 播放
		}
	});
});


/* 	初始化 加载媒体信息
 */
function initJspGrid(){
	
	$('#mediaGrid').datagrid({
	    url:appPath + "/itbMedia/getMediaInfo.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
		checkbox:false,
	    frozenColumns:[[{field:'ck',checkbox:'true',width:10,align:'center',sortable:false}]],
	    columns:[[
			{field:'thumb',title:'缩略图',width:50,align:'center',sortable:false,
				formatter:function(thumb, rowData, rowIndex){
					var retUrl = '';
					var tt = 'http://itbour-user.oss-cn-hangzhou.aliyuncs.com/image/U2/2017/11/06/191334526_2eKu1A5k5LmGoc4fezKI.jpg';
					if (rowData.thumb) {
						tt = rowData.thumb;
					}
					retUrl = '<a href="' + tt + '" target="_blank">'
					+ '<div style="display:table;text-align:center;height:90px;width:100%">'
					+ '<span style="display:table-cell;vertical-align:middle">'
					+ '<img src="' + tt.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com') + '@110h_128w_1l.png'
					+ '" style="display:inline;max-height:90px;max-width:108px"></span></div></a>';
					return retUrl;
				}
			},
	        {field:'media_id',title:'媒体ID',width:35,align:'center',sortable:false,
				formatter:function(value,rowData,rowIndex){
					if (value){
						return '<a href="'+rowData.url+'" target="_blank">'+value+'</a>'
					}
					return 'n/a';
				}
	        },
	        {field:'media_type',title:'媒体类型',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var ret = '未知';
	        		switch(value||'0'){
	        		case 0: ret = '<span style="color:#DEDEDE;">未知</span>'; break;
	        		case 10: ret = '<span style="color:#FF6347;">音频</span>'; break;
	        		case 20: ret = '<span style="color:green;">视频</span>'; break;
	        		}
	        		return ret;
	        	}
	        },
	        {field:'use',title:'应用场景',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var ret = '未知';
	        		switch(value||'0'){
	        		case 0: ret = '<span style="color:#DEDEDE;">未知</span>'; break;
	        		case 10: ret = '<span style="color:#FF6347;">后台用</span>'; break;
	        		case 20: ret = '<span style="color:green;">前端用</span>'; break;
	        		}
	        		return ret;
	        	}
	        },
	        {field:'user_id',title:'用户ID',width:50,align:'center',sortable:false},
	        {field:'nickname',title:'用户名称',width:70,align:'center',sortable:false,
	        	formatter:function(value,rowData,rowIndex){
	        		return value||'<span style="color:#AAAAAA">暂无</span>';
	        	}
	        },
	        {field:'media_name',title:'文件名',width:70,align:'center',sortable:false},
	        {field:'url',title:'资源地址',width:80,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		var type = rowData.media_type;
	        		if (value){
	        			if (type == 10) { // 表示音频资源地址
	        				return '<a href="javascript:void(0)" onclick="playMedia(\''+rowData.url+'\')">音频</a>';
	        			} else {
	        				return '<a href="javascript:void(0)" onclick="playVideo(\''+rowData.thumbs+'\',\''+rowData.url+'\')">视频</a>';
	        			}
	        		}
	        		return '';
	        	}
	        },
	        {field:'duration',title:'时长',width:50,align:'center',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		return value+'/ms'|| '0/ms';
	        	}
	        },
	        {field:'create_time',title:'创建时间',width:80,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:80,align:'center',sortable:false}
	    ]],
	    hideColumn:['user_type'],
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加媒体',
			iconCls:'icon-add',
			handler:function(){
				addMedia();
			}
		},
		{
			text:'删除媒体',
			iconCls:'icon-cancel',
			handler:function(){
				delMedia();
			}
		}]
	    
	});
}

//  播放音频 文件
function playMedia(url){
	if (!url){
		$.messager.alert('警告信息','该音频信息暂时无法播放!','warning');
		return;
	}
	
	$('#playMediaDlg').window({
		title:'音频播放',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	$('#playMediaDlg').window('move',{top:20,left:200});
	$('#playMediaDlg').window('open');
	
	// 展示 音频播放资源
	var htm = '<div style="margin-top:20px;margin-left:80px;"><audio id="audio" controls="controls"><source src="'+url+'" type="audio/mp4"><embed height="100" width="100" src="'+url+'" /></audio></div>';
	$("#mediaUrl").html(htm);
}

//		播放视频资源
function playVideo(thumb,videoUrl){
	$('#playVideoDlg').window({
		title:'视频播放',
		iconCls:'icon-tip',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	if (!videoUrl){
		return $.messager.alert('警告信息','该视频资源暂时无法播放','warning');
	}
	
	$('#playVideoDlg').window('move',{top:20,left:200});
	$('#playVideoDlg').window('open');
	
	// 视频  封面缩略图显示
	if (thumb !== null && thumb.length>0 && thumb!=='null'){
		var retUrl = '<a href="'+thumb+'" target ="_blank" '
		+ '<div style="display:table;text-align:center;height:150px;width:100%">'
		+ '<span style="display:table-cell;vertical-align:middle">'
		+ '<img src="' +thumb+'?x-oss-process=image/resize,m_lfit,h_146,w_250'
		+ '" style="display:inline;max-height:150px;max-width:400px"></span></div></a>';
		$("#videoThumb").html(retUrl);
	}
	
	
	var htm = '<video style="margin-left:20px;height:270px;width:450px;" controls="controls" preload="auto" poster="'+thumb+'" src="'+videoUrl+'"></video>';
	$("#viderUrl").html(htm);
}


// 添加媒体文件
function addMedia(){
	$('#editForm').form('clear');
	$("#ossfile").html('');
	
	$("#editMedType").combobox({
		data:[{type_id : 10,name : '音频'}],
		valueField : 'type_id',
		textField : 'name',
		onLoadSuccess:function(){
			$(this).combobox('select',10).combobox('enable');
		}
	});
	
	$("#editMedUse").combobox({
		data:[{type_id : 10,name : '后台使用'},{type_id : 20,name : '前端使用'}],
		valueField : 'type_id',
		textField : 'name',
		onLoadSuccess:function(){
			$(this).combobox('select',10).combobox('enable');
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title : '新建媒体文件',
		iconCls : 'icon-add',
		modal : true,
		shadow : true,
		collapsible : false,
		minimizable : false,
		maximizable : false
	});

	$('#editDlg').window('move', {
		top : 20,
		left : 20
	});
	$('#editDlg').window('open');
	initOSS();// 初始化上传
}

//	确认提交
function doEdit() {
	var medType = $("#editMedType").combobox('getValue');
	var use = $("#editMedUse").combobox('getValue');
	var sourceUrl=$("p.editUrl1").text(); // 资源地址
	var fileName=$("p.editUrl2").text(); // 资源地址
	
	var myVid = document.getElementById("audio1");
	console.log("duration  ",myVid);
	if(myVid != null){
	     var duration;
	     myVid.load();
	     myVid.oncanplay = function () {  
	            console.log("myVid.duration",myVid.duration);
	            duration = myVid.duration;
	     }
	     
		if (!sourceUrl){
			return $.messager.alert('提示信息','上传的资源地址不能为空!','warning');
		}
	
//		var locArray = sourceUrl.split("/");
//		var file = locArray[locArray.length-1];
//		
//		console.log(file);
		
		$.messager.confirm('提示信息','是否确认新建媒体信息?',function(r){
			if(r){
				var	 url=appPath + "/itbMedia/addMedia.action";// 新建
				var sendData = {
					"meDto.media_type" : medType || 0,
					"meDto.use" : use || 0,
					"meDto.media_name" : fileName || "",
					"meDto.duration" : duration.toFixed(2) || 0,
					"meDto.url" : sourceUrl || ""
				};
				
				if (uploader) {
					uploader.destroy();
					uploader = null;
				}
				$.post(url, sendData, function(data) {
					if (data == "ok") {
						$.messager.alert('提示信息', '提交成功', 'info');
						$('#editDlg').window('close');
						doQuery();
					}else {
						$.message.alert("提示信息", "提交失败", 'info');
					}
				});
			}
		});
	
	}
}

function cancelEdit() {// 取消修改
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
	$('#editDlg').window('close');	
}


function delMedia(){
	$.messager.alert('提示信息','功能暂定','info');
}


function getQueryParam(){
	var queryObject = {};
	var findMediaType = $("#queryMediaType").combobox('getValue');
	var findMediaName=$("#queryMediaName").val();
	if(findMediaType&&findMediaType.length>0) queryObject.findMediaType = findMediaType;
	if(findMediaName&&findMediaName.length>0) queryObject.findMediaName = findMediaName;
	return queryObject;
}

/* 	查询数据
 */
function doQuery(){
	$("#mediaGrid").datagrid('unselectAll');
	$("#mediaGrid").datagrid('load', getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}

/* ***************** OSS for upload
 * ***************** 上传文件到OSS服务器
 */
function initOSS() {
	if (uploader) {
		return;
	}
	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selFiles', 
	    url : 'http://oss.aliyuncs.com',
		init: {
			PostInit: function() {
				document.getElementById('postFiles').onclick = function() {
		            set_upload_param(uploader, '', false);
		            return false;
				};
			},
			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bHasOne = false;// 一次只能上传一个
				plupload.each(files, function(file) {
					if(bHasOne || !isMedia(file.name)) {
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					} else {
						document.getElementById('ossfile').innerHTML += 
	                    	'<div id="'+file.id+'" class="upload_file_info">'+file.name+'('+plupload.formatSize(file.size) +
	                    	')<p class="editUrl1" style="white-space:nowrap;overflow:hidden;"></p><p class="editUrl2" style="white-space:nowrap;overflow:hidden;"></p>'+
	                    	'<div class="upload_progress"><div class="upload_progress_bar" style="width: 0%">'
	                    	+ '</div></div></div>';
						bHasOne = true;
					}
				});
				if (!bHasOne) {
					$.messager.alert('message','必须是媒体文件','info');
				}     
			},
			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },
			UploadProgress: function(up, file) {
				var d = document.getElementById(file.id);
				d.getElementsByTagName('p')[0].innerHTML = '<span>' + file.percent + "%</span>";
	            var prog = d.getElementsByTagName('div')[0];
				var progBar = prog.getElementsByTagName('div')[0];
				progBar.style.width= 2*file.percent+'px';
				progBar.setAttribute('aria-valuenow', file.percent);
			},
			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	console.log(file);
	            	var finUrl='http://itbour-back.oss-cn-hangzhou.aliyuncs.com/'+g_object_name;
	            	document.getElementById(file.id).getElementsByTagName('p')[0].innerHTML =finUrl;
	            	document.getElementById(file.id).getElementsByTagName('p')[1].innerHTML =file.name;
	            	$("a.editUrl").attr('href',finUrl);
	            	$("#divAudio").html('<audio id="audio1" hidden="hidden" src="'+finUrl+'" controls="controls"></audio>')
	            	$.messager.alert('message','上传成功','info');
	            }else {
	            	document.getElementById(file.id).getElementsByTagName('p')[0].innerHTML = info.response;
	            	$.messager.alert('message','上传失败','info');
	            }
			}
		}
	});
	uploader.init();
}

function isMedia(url) {
    var res, suffix = "";
    var imageSuffixes = ["mp3","WAV","AU","SND","RAW","afc","midi","wma","video","aac","m4a"];// 音频文件格式
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;
    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;
var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
  }
	return str;
}

function getSuffix(filename) {
  var pos = filename.lastIndexOf('.');
  var suffix = '';
  if (pos != -1) {
      suffix = filename.substring(pos);
  }
  return suffix;
}

function calculate_object_name(filename) {
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
	g_object_name = "app/U"+g_userId+"/"+nowStr + randomString(20)+"/"+trim(filename);
}

function trim(str){// 去掉名字空格
    return str.replace(/\s|\xA0/g,"");    
}

function set_upload_param(up, filename, ret) {
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
  if (OSS_PARAM.expire < dtNow + 5000) {// 5s
  	var url = appPath+"/itbImg/getOSSToken.action";
      $.get(url, function(data){  
  		if (data && data.signature) { 
  			OSS_PARAM.expire = data.expire;
  			OSS_PARAM.uploadHost = data.uploadHost;
  			OSS_PARAM.accessKeyId = data.accessKeyId;
  			OSS_PARAM.policyBase64 = data.policyBase64;
  			OSS_PARAM.signature = data.signature;
  			OSS_PARAM.flg = true;
  			doUpStart(up, filename, ret);
          } else {
          	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
          }  
      });
  } else {
  	doUpStart(up, filename, ret);
  }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
      calculate_object_name(filename);
  }
  var new_multipart_params = {
      'key' : g_object_name,
      'policy': OSS_PARAM.policyBase64,
      'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
      'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
      'signature': OSS_PARAM.signature,
  };
  up.setOption({
      'url': OSS_PARAM.uploadHost,
      'multipart_params': new_multipart_params
  });
  up.start();
}

function clearUploadList() {
	$(".upload_progress_bar").remove();
	$(".upload_progress").remove();
	$(".upload_file_info").remove();
}
